package com.example.newsapp.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.newsapp.model.UserNewsItem;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class DBHelper extends SQLiteOpenHelper {

    public DBHelper(Context context) {
        super(context, "news.db", null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS history (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "userId TEXT," +
                "newsId TEXT," +
                "title TEXT," +
                "time TEXT," +
                "imageUrl TEXT," +
                "author TEXT," +
                "UNIQUE(userId, newsId))");


    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < 2) {
            db.execSQL("ALTER TABLE history ADD COLUMN author TEXT");
        }
    }

    public void insertOrUpdateHistory(UserNewsItem item) {
        SQLiteDatabase db = getWritableDatabase();

        // 先尝试更新
        int rowsAffected = db.update("history",
                toContentValues(item),
                "userId = ? AND newsId = ?",
                new String[]{String.valueOf(item.getUserId()), String.valueOf(item.getId())});

        // 如果没有更新任何行，则插入
        if (rowsAffected == 0) {
            db.insert("history", null, toContentValues(item));
        }

        db.close();
    }

    private ContentValues toContentValues(UserNewsItem item) {
        ContentValues values = new ContentValues();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String currentTime = sdf.format(new Date());

        item.setTime(currentTime);

        values.put("userId", item.getUserId());
        values.put("newsId", item.getId());
        values.put("title", item.getTitle());
        values.put("time", item.getTime());
        values.put("imageUrl", item.getImageUrl());
        values.put("author", item.getAuthor());
        return values;
    }


    // 查询历史记录
    public List<UserNewsItem> getHistoryByUser(int userId) {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery(
                "SELECT * FROM history WHERE userId = ? ORDER BY time DESC",
                new String[]{String.valueOf(userId)}
        );

        List<UserNewsItem> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            UserNewsItem item = new UserNewsItem();
            item.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("userId")));
            item.setId(cursor.getInt(cursor.getColumnIndexOrThrow("newsId")));
            item.setTitle(cursor.getString(cursor.getColumnIndexOrThrow("title")));
            item.setTime(cursor.getString(cursor.getColumnIndexOrThrow("time")));
            item.setImageUrl(cursor.getString(cursor.getColumnIndexOrThrow("imageUrl")));
            item.setAuthor(cursor.getString(cursor.getColumnIndexOrThrow("author")));
            list.add(item);
        }
        cursor.close();
        db.close();
        return list;
    }

    //清空历史记录
    public void clearHistoryByUser(int userId) {
        SQLiteDatabase db = getWritableDatabase();
        db.delete("history", "userId = ?", new String[]{String.valueOf(userId)});
        db.close();
    }

}
